 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * Project  : WebQQCoreAsync
 * Package  : iqq.im.action
 * File     : LoginAction.java
 * Author   : solosky < solosky772@qq.com >
 * Created  : 2012-9-2
 * License  : Apache License 2.0 
 */
package iqq.mk.action;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import iqq.im.QQActionListener;
import iqq.im.QQException;
import iqq.im.QQException.QQErrorCode;
import iqq.im.action.AbstractHttpAction;
import iqq.im.core.QQConstants;
import iqq.im.core.QQContext;
import iqq.im.core.QQService;
import iqq.im.core.QQSession;
import iqq.im.event.QQActionEvent;
import iqq.im.http.QQHttpCookie;
import iqq.im.http.QQHttpRequest;
import iqq.im.http.QQHttpResponse;
import iqq.im.service.HttpService;
import iqq.im.util.QQEncryptor;

/**
 * <p>WebLoginAction class.</p>
 *
 * @author solosky
 */
public class WebLoginNewAction extends AbstractHttpAction {
	private static final Logger LOG = LoggerFactory.getLogger(WebLoginNewAction.class);
	private String username;
	private String password;
	private long   uin;
	private String verifyCode;

	/**
	 * <p>Constructor for WebLoginAction.</p>
	 *
	 * @param context a {@link iqq.im.core.QQContext} object.
	 * @param listener a {@link iqq.im.QQActionListener} object.
	 * @param username a {@link java.lang.String} object.
	 * @param password a {@link java.lang.String} object.
	 * @param uin a long.
	 * @param verifyCode a {@link java.lang.String} object.
	 */
	public WebLoginNewAction(QQContext context, QQActionListener listener,
			String username, String password, long uin, String verifyCode) {
		super(context, listener);
		this.username = username;
		this.password = password;
		this.uin = uin;
		this.verifyCode = verifyCode;
	}

	/** {@inheritDoc} */
	@Override
	public QQHttpRequest buildRequest() throws QQException {
		/**http://ptlogin2.qq.com/login?
		 * u=398712920&
		 * p=FoB1lU6QzyttKI*qnydVdjBr3oW*qgyX91YuC6YHs*KJSTkzfYj0YoxvHMe*eVIU6DNZag6dbL9iHF35ogu36lcez7jfneXiWWlhnIpecrLIolgYGMEYaOcy8mNqLHXojmAr-cr1EKIeP-2qhBEBroHlfgbUIgxDVN8Q6QpTqLjLQpb6HeWGtFi7ELkgJmIuHScCZY2IAe66F7SHbixEmhnrLvB5LISwqzXSUHpbPE7bnFOoMh-QLp*DSuJdg1jNlIs2nxDb-Q9JOr86w8NhtBP2qXzPKfm1Qsciqd01WZpB1pvJzLequOqz7S7FQ7Bl0dpyZ8HTHjOF6ohEuqUwyQ__&
		 * verifycode=!WVO&
		 * ipFlag=-1&
		 * aid=1600000084&
		 * u1=http%3A%2F%2Fappimg2.qq.com%2Fcard%2Findex_v3.html&
		 * h=1&
		 * ptredirect=1&
		 * ptlang=2052&
		 * daid=4&
		 * from_ui=1&
		 * dumy=&
		 * fp=loginerroralert&
		 * action=3-22-21692&
		 * mibao_css=&
		 * t=1&
		 * g=1&
		 * js_type=0&
		 * js_ver=10176&
		 * login_sig=&
		 * pt_uistyle=6&
		 * pt_randsalt=2&
		 * pt_vcode_v1=0&
		 * pt_verifysession_v1=427bfa9d49bc2bc698e0d6b6c12ea9217fe4cea2170fdd2737a272eb03acc489d3e6299298ebdcbe8886b893807845029bcadbfe27c53c52
		*/
			//尝试登录，准备传递的参数值
		QQHttpRequest req = createHttpRequest("GET", "http://ptlogin2.qq.com/login");
		req.addGetValue("u", username);
		req.addGetValue("p", QQEncryptor.encrypt2(uin, password, verifyCode));
		req.addGetValue("verifycode", verifyCode);
		req.addGetValue("ipFlag", "-1");
		req.addGetValue("aid","1600000084");
		req.addGetValue("u1", "http://appimg2.qq.com/card/index_v3.html");
		req.addGetValue("h", "1");
		req.addGetValue("ptredirect", "1");
		req.addGetValue("ptlang", "2052");
		req.addGetValue("daid", "4");
		req.addGetValue("from_ui", "1");
		req.addGetValue("dumy", "");
		req.addGetValue("fp", "loginerroralert");
		req.addGetValue("action", "3-22-21692");
		req.addGetValue("mibao_css", "");
		req.addGetValue("t", "1");
		req.addGetValue("g", "1");
		req.addGetValue("js_type", "0");
		req.addGetValue("js_ver", "10176");
		req.addGetValue("login_sig", "");
		req.addGetValue("pt_uistyle", "20");
		req.addGetValue("pt_randsalt","2");
		req.addGetValue("pt_vcode_v1", "0");
		
		HttpService httpService = (HttpService) getContext().getSerivce(QQService.Type.HTTP);
		QQHttpCookie ptvfsession = httpService.getCookie("ptvfsession", null);
		if(ptvfsession == null){//验证session在获取验证码阶段得到的。
			ptvfsession = httpService.getCookie("verifysession", null);
		}				
		if(ptvfsession != null)
		{
			 req.addGetValue("pt_verifysession_v1", ptvfsession.getValue());
		}
		
		req.addHeader("Host", "ptlogin2.qq.com");
		
		return req;
	}

	/** {@inheritDoc} */
	@Override
	protected void onHttpStatusOK(QQHttpResponse response) throws QQException {
		Pattern pt = Pattern.compile(QQConstants.REGXP_LOGIN);
	     Matcher mc = pt.matcher(response.getResponseString());
	     LOG.info("WebLogin: " + response.getResponseString());
	     if(mc.find()){
	    	int ret = Integer.parseInt(mc.group(1));
	    	switch(ret){
		    	case 0: getContext().getSession().setState(QQSession.State.ONLINE);
		    			notifyActionEvent(QQActionEvent.Type.EVT_OK, mc.group(3)); 
		    			break;
		    	case 3: throw new QQException(QQErrorCode.WRONG_PASSWORD, mc.group(5));
		    	case 4: throw new QQException(QQErrorCode.WRONG_CAPTCHA, mc.group(5));
		    	case 7: throw new QQException(QQErrorCode.IO_ERROR, mc.group(5));
		    	default: throw new QQException(QQErrorCode.INVALID_USER, mc.group(5));
	    	}
	     }else{
	    	 throw new QQException(QQErrorCode.UNEXPECTED_RESPONSE);
	     }		
	}

}
